setlocale (LC_TIME, "it_IT");
require_once($_SERVER['DOCUMENT_ROOT']."/config.inc.php");
include("funzioni_comuni.php");
/////////// FUNZIONI REVISIONATE /////////////////
function rimuovi_apici($html) {
// utilizzata nella conferma della cancellazione record
return str_replace('"', '"', str_replace("'", "§", $html));
}
// funzioni struttura ad albero
// calcolo del numero di sottocategoria di una categoria
function hafigli($cat, $tabella) {
$res = mysql_query ("select count(id) as tot from $tabella where id_padre = '$cat'");
$row = mysql_fetch_array($res);
$tot=$row['tot'];
return $tot;
}
/*
// calcolo categorie dai padri
function catfigli($cat) {
global $percorsorev, $idout, $tab_cattree, $virgola;
$idout.=$virgola.$cat;
$virgola=",";
$res = mysql_query ("select id from $tab_cattree where id_padre = '$cat'");
while ($row = mysql_fetch_array($res)) {
$idout.=$virgola.$row['id'];
//controlla se ci sono figli
$res2 = mysql_query ("select id from $tab_cattree where id_padre = ".$row['id']);
if (mysql_num_rows($res2)>0) {
catfigli($row['id']);
}
// fine controllo
}
return "(".$idout.")";
}
*/
// breadcrumb
function briciole($cat, $tabella, $pagina, $mode=0) {
//$mode=0 - link attivi
//$mode=1 - link disattivi
global $percorsorev;
$res = mysql_query ("select titolo, id_padre from $tabella where id = '$cat'");
$row = mysql_fetch_array($res);
$link=$mode==1?"/".$row['nome_en']:"/".$row['titolo']."";
$percorsorev = $link.$percorsorev;
if ($row['id_padre']>0) {
briciole($row['id_padre'], $tabella, $pagina, $mode);
}
return $percorsorev;
}
//costruisce il menu ad albero
function select_tree($indice, $tabella, $pagina) {
global $indent, $cat_imgopen, $cat_imgclosed, $cat_imgfile;
$qry = "select id, titolo_menu, id_padre from $tabella where id_padre = $indice order by ranking";
$res = mysql_query ($qry) or die ("Errore $qry" . mysql_error());
while (list($id, $titolo, $id_padre) = mysql_fetch_array($res)) {
//controlla se ci sono figli
$res2 = mysql_query ("select id from $tabella where id_padre = $id");
$chiudiul="";
$apriul ="";
$icona="$cat_imgfile\n";
$link = "".html_entity_decode($titolo, ENT_QUOTES, 'UTF-8')."\n";
if (mysql_num_rows($res2)>0) {
$icona = "$cat_imgclosed\n";
$link = "".html_entity_decode($titolo, ENT_QUOTES, 'UTF-8')."\n";
$apriul = "
\n";
$chiudiul="
\n";
}
// fine controllo
echo "
".$icona.$link;
echo "\n $apriul";
//--- richiamo la funzione
select_tree($id, $tabella, $pagina); //figli
echo $chiudiul;
echo "
";
}
}
function tags_chooser($tab_a, $tab_b, $query, $nameinput, $id=null, $op="init")
{
global $tab_ass;
if($op=='update')
{
mysql_query("DELETE FROM $tab_ass WHERE tab_a = '$tab_a' AND tab_b = '$tab_b' AND a = $id");
foreach($_POST[$nameinput] as $tag)
{
$qu = "INSERT INTO $tab_ass (tab_a, tab_b, a, b) VALUES ('$tab_a', '$tab_b', '$id', '$tag')";
mysql_query($qu);
}
return;
}
if($id!=null)
{
$querytags = "SELECT id, titolo FROM $tab_b JOIN $tab_ass ON $tab_b.id = $tab_ass.b WHERE $tab_ass.a = $id";
$res = mysql_query($querytags);
while($row = mysql_fetch_array($res))
{
$tags .= ''.$row['titolo'].'';
}
}
return "
$tags
";
}
//costruisce la select
function option_tree($indice, $tabella, $attuale=0, $escludi=0) {
// $indice = categoria di partenza; 0 per partire dal livello principale
// $attuale = valore da confrontare per preselezionare la select
// $escludi = id da escludere nella lista valori
$q_esc=$escludi>0?"and id!=$escludi":"";
global $indent, $out;
$qry = "select id, titolo_menu as titolo, id_padre from $tabella where id_padre = $indice $q_esc order by ranking";
$res = mysql_query ($qry) or die ("Errore " . mysql_error(). $qry);
while (list($id, $titolo, $id_padre) = mysql_fetch_array($res)) {
$sel=$attuale==$id?"selected='selected'":"";
$out .= "\n";
//$indent.=" ";
$indent.="-";
option_tree($id, $tabella, $attuale); //figli
$indent = substr($indent, 0, -1);
//$indent = substr($indent, 0, -6);
}
return ("");
}
// fine funzioni struttura ad albero
function parolechiave($keywords, $table, $id_master, $id, $id_lingua) {
$parole=explode(",",$keywords);
mysql_query("delete from $table WHERE id = $id");
foreach($parole as $indice => $parola) {
mysql_query("INSERT into $table (id_master, id, id_lingua, parola) values ($id_master, $id, $id_lingua, '".trim($parola)."')");
}
}
function ricavaparole($table, $id) {
$parole="";
$virgola="";
$query = mysql_query("select parola from $table WHERE id = $id");
while ($rigo = mysql_fetch_array($query)) {
$parole.=$virgola.$rigo['parola'];
$virgola=",";
}
return $parole;
}
function aggiorna_didascalie($newdesc, $id_gruppodl, $desc, $op) {
// op=1 quando si inserisce un record
// op=2 quando si modifica un record
global $tab_files;
$tail="id ASC";
if ($op==2) {
//caso update
$newdesc = array_reverse($newdesc);
$nuovi_allegati = sizeof($newdesc);
$tail="id desc LIMIT $nuovi_allegati";
}
//nuovi inserimenti
$sql = "SELECT id FROM $tab_files where id_gruppodl=$id_gruppodl ORDER BY $tail";
$res = mysql_query($sql);
for($i=0;$riga = mysql_fetch_array($res);$i++) {
$qu = "UPDATE $tab_files SET descrizione = '".$newdesc[$i]."' WHERE id = ".$riga['id'];
mysql_query($qu);
}
//aggiornamento esistenti
foreach($desc as $idcat => $descrizione) {
mysql_query("UPDATE $tab_files SET descrizione = '$descrizione' WHERE id = $idcat");
}
}
function aggiorna_didascalie_lingua($newdesc, $id_gruppodl, $desc, $op, $id_lingua=1) {
// op=1 quando si inserisce un record
// op=2 quando si modifica un record
global $tab_files, $tab_files_desc;
$tail="id ASC";
if ($op==2) {
//caso update
$newdesc = array_reverse($newdesc);
$nuovi_allegati = sizeof($newdesc);
$tail="id desc LIMIT $nuovi_allegati";
}
//nuovi inserimenti
$sql = "SELECT id FROM $tab_files where id_gruppodl=$id_gruppodl ORDER BY $tail";
$res = mysql_query($sql);
for($i=0;$riga = mysql_fetch_array($res);$i++) {
mysql_query("DELETE from $tab_files_desc WHERE id_lingua=$id_lingua and id_file = ".$riga['id']);
mysql_query("INSERT into $tab_files_desc (id_file, id_lingua, lunga) VALUES (".$riga['id'].", $id_lingua, '".$newdesc[$i]."')");
}
//aggiornamento esistenti
foreach($desc as $idcat => $descrizione) {
mysql_query("UPDATE $tab_files_desc SET lunga = '$descrizione' WHERE id_file = $idcat and id_lingua=$id_lingua");
}
}
/////////// FINE FUNZIONI REVISIONATE /////////////////
/*
function slash3 ($campo) {
$transf=$_POST[$campo];
//$transf=str_replace("'", "''", $_POST[$campo]); // per la query
//$transf=str_replace("\'", "''", $_POST[$campo]); // per la query
return($transf);
}
*/
function ajax_choice($tab_destinazione = null, $condizione = null, $display = null, $div_id = null, $id = null, $op = 'init', $key = null)
/*
$tab_destinazione = tabdest della tabella ass_list
$condizione = condizione sulla tabella di origine Es: "FROM $tab_utenti WHERE nome LIKE \"%@@@%\" OR cognome LIKE \"%@@@%\"";
$display = campi da visualizzare nel formato "@nome@ @cognome@"
$div_id = nome del div che contiene le voci progressive
$id = id record tabella destinazione
$op = operazione: init => inizializzazione sistema autosuggest; update => aggiornamento valori database, view => sola lettura
$key = valore immesso (serve in $op = suggest in maggiordomo.php)
*/
{
$i=0;
if($op=='init')
{
/*
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_RAND);
$condizionec = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, '37asu', $condizione, MCRYPT_MODE_CFB, $iv);
$displayc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, '37asu', $display, MCRYPT_MODE_CFB, $iv);
*/
$out .= "
";
}
//$display = "%nome% %cognome%"
preg_match_all('/@([a-z-_\d]+)@/i', $display, $campi, PREG_PATTERN_ORDER);
#print_r($campi[0]);
foreach($campi[1] as $indice => $campo)
{
$d .= $i==0 ? "":", ";
$i++;
$d .= $campo;
}
global $tab_ass;
if($op=='update')
{
mysql_query("DELETE FROM $tab_ass WHERE tabledest = '$tab_destinazione' AND id_tabledest = ".$id);
foreach($_POST as $post => $cc)
{
if(is_array($cc))
{
foreach($cc as $vv)
{
$qu = "INSERT INTO $tab_ass (tableo, id_table, tabledest, id_tabledest) VALUES ('$post', $vv, '$tab_destinazione', $id)";
mysql_query($qu);
}
}
}
return;
}
if($op=='init' OR $op=='view')
{
$q = "SELECT $tab_ass.tableo, $tab_ass.id_table FROM $tab_ass WHERE tabledest = '$tab_destinazione' AND id_tabledest = $id";
$res = mysql_query($q);
while($riga = mysql_fetch_array($res))
{
$contatto_d = $display;
$contatto = trova("id", $riga['id_table'], $d, $riga['tableo']);
foreach($campi[0] as $ii => $v)
{
$contatto_d = str_replace($v, $contatto[$campi[1][$ii]], $contatto_d);
}
$edit = $op=='view' ? "":"x";
$out .= "
";
}
function close_lightbox($id=null,$nuovi=null,$funzione=null,$urlie=null) {
if($id==null) {
if($_REQUEST['naked']==1) {
echo '';
return;
}
else {
echo '';
return;
}
}
if($_REQUEST['naked']==1) {
echo '';
}
else {
echo '';
}
}
// ++++++++ FUNZIONI PER INTERAZIONE CON IL DB ++++++++ //
function ordina($tabella,$div = 'myList', $page, $cat) {
// $page = pagina dell'eventuale menù da rivisualizzare; $cat=categoria padre
$refreshmenu=$page!=""?"caricasx($cat, '$page');":"";
$output="
";
return $output;
}
// ******** FINE FUNZIONI PER INTERAZIONE CON IL DB ******** //
/*
/// FUNZIONI Su DATE - UTILI SE C'E' IL MODULO STATISTICHE
Function QuantiGiorni($data1,$data2)
{
//calcola i giorni di differenza tra due date
//data1 e 2 in formato yyyy-mm-dd
$query = mysql_query("select to_days('$data2')-to_days('$data1') as tot ");
return $total = mysql_result($query,0,'tot');
}
function giornidelmese($Mese, $Anno) {
$giorni_settimana = array("D","L","M","M","G","V","S");
$mese_testo = array(1 => "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre"," Dicembre");
$mese_testo_ing = array(1 => "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"," December");
if (($Mese+1)>12) {
$M1=1;
$A1=$Anno+1;
} else {
$M1=$Mese+1;
$A1=$Anno;
}
$DD1=QuantiGiorni("2000-01-01",$Anno."-".$Mese."-01");
$DD2=QuantiGiorni("2000-01-01",$A1."-".$M1."-01");
$cicli= (($DD2)-$DD1);
$giornimese=array();
for ($i = 1; $i <= $cicli; $i++) {
$giorno=$giorni_settimana[date("w",strtotime ($i." $mese_testo_ing[$Mese] $Anno"))];
$dispdate=$i<10?"0".$i."-".$giorno:$i."-".$giorno;
//$dispdate=$giorno=="D"?"".$dispdate."":$dispdate;
$giornimese[] = $dispdate;
}
return $giornimese;
}
*/
function valid_email($email) {
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) return true; else return false;
}
function file_extension($fname) {
return strtolower(substr(strrchr($fname, '.'), 1));
}
function resize_image($id, $tn_max_width=160, $tn_max_height=160) {
global $path_up, $tab_files;
$fname = trova("id", $id, 'nome_file', $tab_files);
$picname = $fname;
$size = getimagesize($path_up.$fname);
$width = $size[0];
$height = $size[1];
if($width>$height) {
mysql_query("UPDATE $tab_files SET orizzontale = 1 WHERE id = $id");
}
$max_width = 800;
$max_height = 600;
//IMG ORIG!
if (($width <= $max_width) AND ($height <= $max_height)) {
$orig_width = $width;
$orig_height = $height;
}
else {
if ($height > $width) {
$riduzione = $height / $max_height;
$orig_width = $width / $riduzione;
$orig_height = $max_height;
}
else {
$riduzione = $width / $max_width;
$orig_height = $height / $riduzione;
$orig_width = $max_width;
}
}
$ext = file_extension($fname); // get the file extension
switch ($ext) {
case 'jpg': // jpg
$image = imagecreatefromjpeg($path_up.$fname);
break;
case 'png': // png
$image = imagecreatefrompng($path_up.$fname);
break;
case 'gif': // gif
$image = imagecreatefromgif($path_up.$fname);
break;
default:
exit('formato immagine non supportato');
}
unlink($path_up.$fname);
$image_orig = imagecreatetruecolor($orig_width, $orig_height);
switch ($ext) {
case 'jpg': // jpg
imagecopyresampled($image_orig, $image, 0, 0, 0, 0, $orig_width, $orig_height, $width, $height);
imagejpeg($image_orig, $path_up.$picname, 80);
break;
case 'png': // png
imagealphablending($image_orig, false);
imagecopyresampled($image_orig, $image, 0, 0, 0, 0, $orig_width, $orig_height, $width, $height);
imagesavealpha($image_orig, true);
imagepng($image_orig, $path_up.$picname, 80);
break;
case 'gif': // gif
$image_orig = imagecreatetruecolor($orig_width, $orig_height);
imagesavealpha($image_orig,true);
$white = imagecolorallocate($image_orig, 0xff, 0xff, 0xff);
imagefill($image_orig, 0, 0, $white);
imagecopyresampled($image_orig, $image, 0, 0, 0, 0, $orig_width, $orig_height, $width, $height);
imagegif($image_orig, $path_up.$picname);
}
imageDestroy($image);
imageDestroy($image_orig);
}
function delete_file($id, $type) {
global $path_up, $tab_files, $tab_files_desc;
if ($type=="single") {
$query = "select nome_file from $tab_files where id = ".$id;
$rigo = mysql_fetch_array(mysql_query($query));
@unlink($path_up.$rigo['nome_file']);
@unlink($path_up."tn_".$rigo['nome_file']);
mysql_query("delete from $tab_files_desc where id_file = ".$id);
mysql_query("delete from $tab_files where id = ".$id);
}
if ($type=="all") {
$query = "select id, nome_file from $tab_files where id_gruppodl = ".$id;
$res = mysql_query($query);
while ($rigo = mysql_fetch_array($res)) {
@unlink($path_up.$rigo['nome_file']);
@unlink($path_up."tn_".$rigo['nome_file']);
mysql_query("delete from $tab_files_desc where id_file = ".$rigo['id']);
}
mysql_query("delete from $tab_files where id_gruppodl = ".$id);
}
}
function video_preview($id)
{
global $path_up, $tab_files;
$fname = trova("id", $id, 'nome_file', $tab_files);
$thumbname = $fname.".jpg";
require_once $_SERVER["DOCUMENT_ROOT"].'/inc/videotools/examples/example-config.php';
require_once $_SERVER["DOCUMENT_ROOT"].'/inc/videotools/phpvideotoolkit.'.$use_version.'.php';
$tmp_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH.'tmp/';
$files_to_process = array($_SERVER["DOCUMENT_ROOT"].'/inc/files/'.$fname);
$log_dir = PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH.'logs/';
$toolkit = new PHPVideoToolkit($tmp_dir);
$toolkit->on_error_die = FALSE;
$total_process_time = 0;
foreach($files_to_process as $key=>$file)
{
// get the filename parts
$filename = basename($file);
$filename_minus_ext = substr($filename, 0, strrpos($filename, '.')).rand(1,1000000);
// set the input file
$ok = $toolkit->setInputFile($file);
// check the return value in-case of error
if(!$ok)
{
// if there was an error then get it
echo ''.$toolkit->getLastError()." \r\n";
$toolkit->reset();
continue;
}
// set the output dimensions
$toolkit->setVideoOutputDimensions('300x200');
// extract a thumbnail from the fifth frame two seconds into the video
$toolkit->extractFrame('3.1');
// set the output details
$ok = $toolkit->setOutput($_SERVER["DOCUMENT_ROOT"].'/inc/files/', $thumbname, PHPVideoToolkit::OVERWRITE_EXISTING);
// check the return value in-case of error
if(!$ok)
{
// if there was an error then get it
echo ''.$toolkit->getLastError()." \r\n";
$toolkit->reset();
continue;
}
// execute the ffmpeg command
$result = $toolkit->execute(false, true);
// get the last command given
// $command = $toolkit->getLastCommand();
// echo $command." \r\n";
// check the return value in-case of error
if($result !== PHPVideoToolkit::RESULT_OK)
{
// move the log file to the log directory as something has gone wrong
$toolkit->moveLog($log_dir.$filename_minus_ext.'.log');
// if there was an error then get it
echo ''.$toolkit->getLastError()." \r\n";
$toolkit->reset();
continue;
}
// get the process time of the file
$process_time = $toolkit->getLastProcessTime();
$total_process_time += $process_time;
$file = array_shift($toolkit->getLastOutput());
// reset
$toolkit->reset();
}
}
function php_upload($file, $tab, $idgruppo, $userid) {
include("json.php");
global $tab_files, $path_up;
$result = array();
$file = $_FILES['fileupload']['tmp_name'];
$error = false;
$size = false;
if (!is_uploaded_file($file) || ($_FILES['fileupload']['size'] > 100 * 1024 * 1024) ) {
$error = 'Upload Fallito! Non è possibile caricare un file maggiore di 100MB';
}
if ($_FILES["fileupload"] != "") {
$nome_allegato = str_replace(" ", "", $_FILES["fileupload"]["name"]);
$trova_punto_allegato = explode(".", $nome_allegato);
$estensione_allegato = $trova_punto_allegato[count($trova_punto_allegato) - 1];
$estensione_allegato = strtolower($estensione_allegato);
}
$allegato_inserito=time()."_".rand(0,999999).".$estensione_allegato";
@move_uploaded_file($_FILES["fileupload"]["tmp_name"], $path_up.$allegato_inserito);
@chmod($path_up.$allegato_inserito, 0775);
if (file_exists($path_up.$allegato_inserito)) {
$sql="insert into $tab_files (id_gruppodl,nome_file,tipo,nome_utf8,tipo_allegato,id_utente,data_ins) VALUES ($idgruppo,'$allegato_inserito','$estensione_allegato', '".addslashes($nome_allegato)."', '".cerca_tipo($estensione_allegato)."', '".$userid."', NOW())";
$query = mysql_query ($sql) or die (mysql_error().$sql);
$id = mysql_insert_id();
$tipo_file = cerca_tipo(file_extension($_FILES["fileupload"]["name"]));
if ($tipo_file=="immagine") resize_image($id);
if ($tipo_file=="video") video_preview($id);
} else $error = "File Non caricato! $path_up $allegato_inserito";
if ($error) {
$result['result'] = 'failed';
$result['error'] = $error;
}
else {
$result['result'] = 'success';
$result['size'] = "File Caricato";
$result['post'] = '';
}
header('Content-type: application/json');
$json = new Services_JSON();
exit($json->encode($result));
}
// FUNZIONE AJAX UPLOADER //
// ---------------------- //
/*
@ input **
*
* FILE CARICABILI
*
* si può indicare nell'argomento input:
* - una stringa (tipo file ammesso per upload singolo)
* es. "immagine" permetterà l'upload di un file del tipo "immagine"
*
* - un array (per upload multipli) es. $array_upload
* con $array_upload = array ("immagine"=>3,"documento"=>0,"video"=>1,"dwg"=>1)
* che permetterà l'upload * di max 3 immagini, n documenti, max 1 video, max 1 file con estensione dwg
*
* macrosezioni tipi di file: immagine, documento, video
@ tab **
* nome tabella in cui vengono memorizzati i dati degli allegati
@ form **
*
* FORM (input, textarea, textarea con classe 'widgEditor')
*
* es.
@ id **
* IDENTIFICATIVO ARTICOLO / DOWNLOAD / PARAGRAFO / ETC
@ pagurl **
* URL destinazione FORM
* es. "?page=accreditamenti"
@ onsubmit **
* eventuale codice javascript da eseguire al submit del form dati. ES: onsubmit='onsubmit="return validate()"'
@ des **
* des=1 se serve il campo descrizione per ogni singolo allegato
@ tipouploader **
* valore della variabile tipo passato attraverso javascript per scopi diversi
*(Es: viene utilizzato il valore repository nel javascript che valida l'immissione di almeno un allegato
@ elencofiles **
* 1 = mostra nel form di immissione eventuale elenco di files già inseriti
* 0 = mostra nel form di immissione solo il link per immettere o sostituire l'allegato
*/
function ajax_uploader($input,$tab,$form,$id = 0,$pagurl,$onsubmit=null,$des=0,$tipouploader="standard", $elencofiles=1, $lang=0, $id_lingua=1) {
global $url, $path_up, $ar_tipi_files, $tab_files, $tab_files_desc;
// preg_match_all('/